#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <string>

using std::cout;
using std::endl;
using std::string;

void SetNoBack(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        printf("error, code:%d msg:%s\n", errno, strerror(errno));
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    SetNoBack(0);
    char buffer[128];

    while (1)
    {
        bzero(buffer, sizeof(buffer));
        
        int n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            string s = "I get message: ";
            s += buffer;
            cout << s << endl;
        }
        else if (n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            if (errno == EWOULDBLOCK)
            {
                cout << "no message" << endl;
                sleep(1);
                continue;
            }
            else
            {
                printf("error, code:%d msg:%s\n", errno, strerror(errno));
                break;
            }
        }
    }
    return 0;
}
